<script lang="ts" setup>
import { useApplyStore, useAuthStore } from '@/store'
import file from '@/api/file'
import { getEnv } from '@/utils/shared.ts'

const props = defineProps({
  type: {
    type: String,
  },
  sourceType: {
    type: Array<string>,
    default: ['camera'],
  },
})

const emits = defineEmits(['uploaded'])
const { applyId, imageList } = storeToRefs(useApplyStore())
const { token, sessionid } = storeToRefs(useAuthStore())
const uploadUrl = ref(getEnv().apiBase + '/napFileApi/merchant/common/file/upload')
const formHeader = {
  'Content-Type': 'form-data',
  'X-Authorization': token.value,
}
const formData1 = {
  sessionid: sessionid.value,
  businessId: applyId.value,
  refType: '5',
  refId: '1',
  bindingType: '1',
}

const formData2 = {
  sessionid: sessionid.value,
  businessId: applyId.value,
  refType: '6',
  refId: '1',
  bindingType: '1',
}

if (props.type === 'operator') {
  formData1.refType = '51'
  formData2.refType = '52'
}

const fileList1 = ref<any[]>([])
const fileList2 = ref<any[]>([])
onMounted(async () => {
  const file1 = imageList.value[`fileType${formData1.refType}`]
  if (file1 && file1.name !== '') {
    file1.status = 'uploading'
    file1.message = '载入中'
    fileList1.value.push(file1)
    file1.url = await file.downloadImage(file1.name)
    file1.status = 'success'
  }
  const file2 = imageList.value[`fileType${formData2.refType}`]
  if (file2 && file2.name !== '') {
    file2.status = 'uploading'
    file2.message = '载入中'
    fileList2.value.push(file2)
    file2.url = await file.downloadImage(file2.name)
    file2.status = 'success'
  }
})


async function beforeZhengUpload (UploadFile: any, options: any) {
  // UploadFile  是 uni.uploadFile ， 你也可以自定义设置其它函数
  UploadFile({
    url: options.url,
    filePath: options.filePath,
    fileType: options.fileType,
    header: {
      'Content-Type': 'multipart/form-data',
      'X-Authorization': token.value,
      ...options.headers
    }, //
    formData: options.formData,
    name: options.name,
    success(response: { errMsg: any; statusCode: number; data: string }) {
      if (options.xhrState == response.statusCode) {
        options.onSuccess?.(response, options);
      } else {
        options.onFailure?.(response, options);
      }
    },
    fail(e: any) {
      options.onFailure?.(e, options);
    }
  });
  // 先查是否已经有图片了
  const file1 = imageList.value[`fileType${formData1.refType}`]
  if (file1 && file1.url !== '') {
    // 调用图片删除接口
    const { data } = await file.delImage(file1.name)
    if (data.status === 'success') {
      options.onStart?.(options);
    }
  } else {
    options.onStart?.(options);
  }
} 
async function beforeBeiUpload (UploadFile: any, options: any) {
  // UploadFile  是 uni.uploadFile ， 你也可以自定义设置其它函数
  UploadFile({
    url: options.url,
    filePath: options.filePath,
    fileType: options.fileType,
    header: {
      'Content-Type': 'multipart/form-data',
      'X-Authorization': token.value,
      ...options.headers
    }, //
    formData: options.formData,
    name: options.name,
    success(response: { errMsg: any; statusCode: number; data: string }) {
      if (options.xhrState == response.statusCode) {
        options.onSuccess?.(response, options);
      } else {
        options.onFailure?.(response, options);
      }
    },
    fail(e: any) {
      options.onFailure?.(e, options);
    }
  });
  // 先查是否已经有图片了
  const file2 = imageList.value[`fileType${formData2.refType}`]
  if (file2 && file2.url !== '') {
    // 调用图片删除接口
    const { data } = await file.delImage(file2.name)
    if (data.status === 'success') {
      options.onStart?.(options);
    }
  } else {
    options.onStart?.(options);
  }
}

function uploadZhengSuccess({ responseText }) {
  if (responseText.statusCode === 200) {
    const data = JSON.parse(responseText.data)
    if (data.status === 'success') {
      emits('uploaded', {
        type: formData1.refType,
        certName: data.data.certInfo.certName,
        certNo: data.data.certInfo.certNo.toLocaleUpperCase(),
        certAddr: data.data.certInfo.certAddr,
      })
      imageList.value[`fileType${formData1.refType}`].name = fileList1.value[0].name
      imageList.value[`fileType${formData1.refType}`].url = fileList1.value[0].url
    } else {
      // 如果失败将置空所有
      emits('uploaded', {
        type: formData1.refType,
        certName: '',
        certNo: '',
        certAddr: '',
      })
    }
  }
}
function uploadBeiSuccess({ responseText }) {
  if (responseText.statusCode === 200) {
    const data = JSON.parse(responseText.data)
    if (data.status === 'success') {
      emits('uploaded', {
        type: formData2.refType,
        certStartDate: data.data.certOtherInfo.certStartDate,
        certEndDate: data.data.certOtherInfo.certEndDate,
      })
      imageList.value[`fileType${formData2.refType}`].name = fileList2.value[0].name
      imageList.value[`fileType${formData2.refType}`].url = fileList2.value[0].url
    }else {
      uni.showModal({
        title: '识别提示',
        content: data.message
      })
      // 如果失败将置空所有
      emits('uploaded', {
        type: formData2.refType,
        certStartDate: '',
        certEndDate: '',
      })
    }
  }
}

function uploadFailure(res) {
  console.log('uploadFailure')
  console.log(res)
}

function validate() {
  const pool: any = {
    zheng: true,
    bei: true,
  }
  return new Promise((resolve) => {
    if (fileList1.value.length === 0) {
      pool.zheng = false
    }
    if (fileList2.value.length === 0) {
      pool.bei = false
    }
    resolve(pool)
  })
}

defineExpose({ validate })

function previewImage(list) {
  if (list.length === 0) {
    return
  }
  uni.previewImage({
    urls: [list[0].url],
  })
}
</script>

<template>
  <div class="cert-loader">
    <div class="loader">
      <nut-uploader v-model:file-list="fileList1" :source-type="sourceType" :url="uploadUrl" :data="formData1"
        :headers="formHeader" maximum="1" :before-upload="beforeZhengUpload" @success="uploadZhengSuccess"
        @failure="uploadFailure" @file-item-click="previewImage(fileList1)">
        <template #uploadIcon>
          <div>
            <image src="/src/static/sfz_z.png" mode="widthFix" class="sfz_img" />
          </div>
        </template>
      </nut-uploader>
      <div class="title">身份证人像面</div>
    </div>
    <div class="loader" style="margin-left: 20rpx;">
      <nut-uploader v-model:file-list="fileList2" :source-type="sourceType" :url="uploadUrl" :data="formData2"
        :headers="formHeader" maximum="1" :before-upload="beforeBeiUpload" @success="uploadBeiSuccess"
        @failure="uploadFailure" @file-item-click="previewImage(fileList2)">
        <template #uploadIcon>
          <div>
            <image src="/src/static/sfz_f.png" mode="widthFix" class="sfz_img" />
          </div>
        </template>
      </nut-uploader>
      <div class="title">身份证国徽面</div>
    </div>
  </div>
</template>

<style lang="sass" scoped>
.cert-loader
  width: 100%
  display: flex
  justify-content: space-between
  .loader
    flex: 1
    .title
      text-align: center
      color: #8e8e8e
      margin-top: 5px
      font-size: 12px

.sfz_img
  width: 343rpx

</style>
